package com.usian.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.usian.admin.feign.ArticleFeign;
import com.usian.admin.feign.WemediaFeign;
import com.usian.admin.service.AdSensitiveService;
import com.usian.admin.service.WemediaNewsAutoScanService;
import com.usian.common.aliyun.GreeTextScan;
import com.usian.common.aliyun.GreenImageScan;
import com.usian.common.fastdfs.FastDFSClientUtil;
import com.usian.model.admin.pojos.AdSensitive;
import com.usian.model.article.pojos.ApArticle;
import com.usian.model.article.pojos.ApArticleConfig;
import com.usian.model.article.pojos.ApArticleContent;
import com.usian.model.article.pojos.ApAuthor;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.media.pojos.WmNews;
import com.usian.utils.common.SensitiveWordUtil;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class WemediaNewsAutoScanServiceImpl implements WemediaNewsAutoScanService {
    @Autowired
    WemediaFeign wemediaFeign;
    @Autowired
    ArticleFeign articleFeign;
    @Autowired
    GreeTextScan greeTextScan;
    @Autowired
    GreenImageScan greenImageScan;
    @Autowired
    AdSensitiveService adSensitiveService;
    @Autowired
    private KafkaTemplate kafkaTemplate;
    @Value("${fdfs.ur1}")
    private String fileServerUrl;
    @Autowired
    private FastDFSClientUtil fastDFSClientUtil;
    @SneakyThrows
    @Override
    public void autoScanByMediaNewsId(Integer id) {
        //根据id查询文章
        WmNews  data = wemediaFeign.findById(id);
        //判断news状态
        //当前的状态==4
        if (data.getStatus()==4){
            //a.如status是 4人工市核通过 保存数据即可在article库给三个表额加数据
            // ap_article、ap_artice_config、ap_article_content
            // 编写保存文产数据的方法
            saveArticleAll(data);
        }
        //状态==8
        if (data.getStatus()==8){
            if (data.getPublishTime().getTime()<=System.currentTimeMillis()){
                saveArticleAll(data);
                return;
            }
        }
        //状态为1
        if (data.getStatus()==1){
            //提取内容
            String content=getContent(data);
            //提取图片
            List<String> image=getImage(data);
            //自管理名词汇审核
            if (!wordScan(data))return;
            //阿里云的文本审核
            if (!textScan(content))return;
            //阿里云的图片审核
            if (!imageScan(image, data))return;
            //判定当前文章的发布时间大于当前
            if (data.getPublishTime().getTime()>System.currentTimeMillis()){
                data.setReason("审核通过，待发布");
                data.setStatus(8);
                wemediaFeign.updateWmNews(data);
                return;
            }
            saveArticleAll(data);
        }
    }
    //审核敏感词汇
    public boolean wordScan(WmNews wmNews){
        boolean falg=true;
        List<AdSensitive> list=adSensitiveService.findAll();
        //提取list集合中sensitive的敏感词
        List<String> word=new ArrayList<>();
        for (AdSensitive adSensitive : list) {
            word.add(adSensitive.getSensitives());
        }
        SensitiveWordUtil.initMap(word);
        Map<String, Integer> map = SensitiveWordUtil.matchWords(getContent(wmNews));
        if (map.size()>0){
            falg=false;
            wmNews.setStatus(2);
            wmNews.setReason("文中含有敏感词汇");
            wemediaFeign.updateWmNews(wmNews);
        }
        return falg;
    }

    //审核图片
    public boolean imageScan(List<String> images,WmNews wmNews) throws Exception {
        boolean falg=true;
        Integer status=0;
        String msg="";
        List<byte[]> imageList=new ArrayList<>();
        for (String image : images) {
            String imageName=image.replace(fileServerUrl, "");
            int index=imageName.indexOf("/");
            String groupName=imageName.substring(0, index);
            String imagePath =imageName.substring(index+1);
            byte[] imageByte=fastDFSClientUtil.download(groupName, imagePath);
            imageList.add(imageByte);
        }
        Map map = greenImageScan.imageScan(imageList);
        String result=(String)map.get("suggestion");
        if (result.equals("block")){
            status=2;
            msg="图中有敏感词汇";
            falg=false;
        }else if (result.equals("review")){
            status=3;
            msg="图片内容不确定，待人工审核";
            falg=false;
        }
        wmNews.setStatus(status);
        wmNews.setReason(msg);
        if (falg){
            wemediaFeign.updateWmNews(wmNews);
        }
        return falg;
    }
    //从data中提取出文本
    public String getContent(WmNews wmNews){
        String str="";
        List<Map> maps = JSON.parseArray(wmNews.getContent(),Map.class);
        for (Map map : maps) {
            if (map.get("type").equals("text")){
                str=(String)map.get("value");
            }
        }
        return str;
    }
    //提取图片
    public List<String> getImage(WmNews wmNews){
        List<String> list=new ArrayList<>();
        List<Map> maps = JSON.parseArray(wmNews.getContent(),Map.class);
        for (Map map : maps) {
            if (map.get("type").equals("image")){
                list.add(map.get("value").toString());
            }
        }
        return list;
    }
    //文字审核
    public boolean textScan(String str) throws Exception {
        boolean falg=true;
        WmNews wmNews = new WmNews();
        Integer status=0;
        String msg="";
        Map map = greeTextScan.greeTextScan(str);
        String result=(String)map.get("suggestion");
        if (result.equals("pass")){
            status=9;
            msg="审核通过";
        }else if (result.equals("block")){
            status=2;
            msg="文字有敏感词汇";
            falg=false;
        }else {
            status=3;
            msg="内容不确定。待人工审核";
            falg=false;
        }
        wmNews.setStatus(status);
        wmNews.setReason(msg);
        if (falg){
            wemediaFeign.updateWmNews(wmNews);
        }
        return falg;
    }
    //融合
    public void  saveArticleAll(WmNews wmNews){
        ApArticle  apArticle=saveArticle(wmNews);
        saveArticleContent(wmNews, apArticle);
        saveArticleConfig(wmNews, apArticle);
        wmNews.setStatus(9);
        wmNews.setReason("审核通过");
        wmNews.setArticleId(apArticle.getId());
        wemediaFeign.updateWmNews(wmNews);
    }
    //保存article
    public ApArticle saveArticle(WmNews wmNews){
        ApArticle apArticle = new ApArticle();
        //赋值
        apArticle.setChannelId(wmNews.getChannelId());
        apArticle.setImages(wmNews.getImages());
        apArticle.setTitle(wmNews.getTitle());
        apArticle.setLayout(wmNews.getType());
        ApAuthor apAuthor = articleFeign.findUserId(wmNews.getUserId());
        apArticle.setAuthorId(apAuthor.getId().longValue());
        apArticle.setAuthorName(apAuthor.getName());
        apArticle.setCreatedTime(wmNews.getCreatedTime());
        apArticle.setPublishTime(wmNews.getPublishTime());
        ApArticle apArticle1 = articleFeign.saveArticle(apArticle);
        System.out.println(apArticle1.toString()+"---------------------");
        return apArticle1;
    }
    //保存ap-article-config
    public void saveArticleConfig(WmNews wmNews,ApArticle apArticle){
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setArticleId(apArticle.getId());
        apArticleConfig.setIsDown(true);
        apArticleConfig.setIsDelete(false);
        apArticleConfig.setIsForward(false);
        apArticleConfig.setIsComment(true);
        ResponseResult responseResult = articleFeign.saveArticleConfig(apArticleConfig);
    }
    //保存ap_article_content
    public void saveArticleContent(WmNews wmNews,ApArticle apArticle){
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(apArticle.getId());
        apArticleContent.setContent(wmNews.getContent());
        ResponseResult responseResult = articleFeign.saveArticleContent(apArticleContent);
    }
}
